﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Text;
using System.Data;
using System.IO;
using Exam.Core;
using System.Collections;
using System.Xml;

public partial class Manage_Service_addPaper : ManagePageBase {

    Exam.Core.DAL.Paper dal = new Exam.Core.DAL.Paper();

    protected void Page_Load(object sender, EventArgs e) {
        //Thread.Sleep(10 * 1000);
        string result = "0";
        //Response.Write("1");
        string pname = Request.Form["pname"].Trim();
        string ptime = Request.Form["ptime"].Trim();
        string ptype = Request.Form["ptype"].Trim();
        string pdesc = Request.Form["pdesc"].Trim();
        string startime = Request.Form["startime"].Trim();
        string endtime = Request.Form["endtime"].Trim();
        string students = Request.Form["students"].Trim();
        string qtype = Request.Form["qtype"].Trim();//题型
        string tactics = Request.Form["tactics"].Trim();//出题数量
        string course = Request.Form["course"].Trim();
        string dept = Request.Form["dept"].Trim();
        string allowre = Request.Form["AllowRe"].Trim();

        //根据策略生成XML格式试卷
        string[] questionType = qtype.Trim(',').Split(',');
        string[] papertactics = tactics.Trim(',').Split(',');



        StringBuilder sbTactics = new StringBuilder();
        StringBuilder sb = new StringBuilder();

        //sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
        //sb.Append("<root>");
        //sb.Append("<content>");

        XmlText xmltext;
        XmlDocument xmldoc = new XmlDocument();
        XmlNode xmlnode = xmldoc.CreateXmlDeclaration("1.0", "utf-8", null);
        xmldoc.AppendChild(xmlnode);

        XmlElement root = xmldoc.CreateElement("", "root", "");
        xmltext = xmldoc.CreateTextNode("");
        root.AppendChild(xmltext);
        xmldoc.AppendChild(root);

         

        XmlElement content = xmldoc.CreateElement("", "content", "");
        xmltext = xmldoc.CreateTextNode("");
        content.AppendChild(xmltext);
        xmldoc.ChildNodes.Item(1).AppendChild(content);

        XmlElement paperTactics = xmldoc.CreateElement("", "paperTactics", "");
        xmltext = xmldoc.CreateTextNode("");
        paperTactics.AppendChild(xmltext);
        xmldoc.ChildNodes.Item(1).AppendChild(paperTactics);


        for (int i = 0; i < questionType.Length; i++) {
            string[] tmpType=questionType[i].Trim('_').Split('_');

            XmlElement questiontype = xmldoc.CreateElement("", "questiontype", "");
            xmltext = xmldoc.CreateTextNode("");
            questiontype.AppendChild(xmltext);
            questiontype.SetAttribute("id", "", tmpType[0].Trim());
            questiontype.SetAttribute("score", tmpType[1].Trim()); 
            xmldoc.ChildNodes.Item(1).AppendChild(content).AppendChild(questiontype);


            XmlElement questiontype1 = xmldoc.CreateElement("", "questiontype", "");
            xmltext = xmldoc.CreateTextNode("");
            questiontype1.AppendChild(xmltext);
            questiontype1.SetAttribute("id", "", tmpType[0].Trim());
            questiontype1.SetAttribute("score", tmpType[1].Trim());
            xmldoc.ChildNodes.Item(1).AppendChild(paperTactics).AppendChild(questiontype1);//策略
            

            #region
            List<String> SQLStringList = new List<String>();
            foreach (string str in papertactics) {
                string[] ArrStr = str.Split('_');
                //判断是否当前题型的策略
                if (ArrStr[2].Trim() == tmpType[0].Trim()) {
                    SQLStringList.Add(getSql(ArrStr, course));
                    sbTactics.Append(str+",");
                }
            }
            #endregion
            string ids = dal.QuestionIDList(SQLStringList);

            XmlElement questionid = xmldoc.CreateElement("", "questionid", "");
            xmltext = xmldoc.CreateTextNode("");
            questionid.AppendChild(xmltext);
            questionid.InnerText = ids.Trim();
            xmldoc.ChildNodes.Item(1).AppendChild(content).AppendChild(questiontype).AppendChild(questionid);

            //策略
            xmldoc.ChildNodes.Item(1).AppendChild(paperTactics).AppendChild(questiontype1).InnerText = sbTactics.ToString().Trim(',').Trim();

            sbTactics.Length = 0;
            SQLStringList.Clear();

        }

        string paperFileName = DateTime.Now.ToString("yyyyMMddhhmmss").Trim() + ".xml";
        string path = FilePath.PaperPath.Trim() + paperFileName;
        if (!File.Exists(path)){
            File.Delete(path);
        }
        xmldoc.Save(path); //保存 


        //写入试卷表
        int paperId = dal.Add(pname, ptime, ptype, pdesc,DateTime.Now.ToString(), startime, endtime, paperFileName, course, dept, allowre);
        if (paperId > 0) {
            //试卷与考生关联
            string[] ArrStudent = students.Trim(',').Split(',');
            
            ArrayList StudentPaper = new ArrayList();
            foreach (string stuId in ArrStudent) {
                if (stuId.Trim() != "") {
                    StudentPaper.Add("INSERT INTO StudentPaper(StudentID,PaperID)VALUES(" + stuId + "," + paperId + ")");
                }
            }
            
            if(dal.AddStudentPaper(StudentPaper)>0){
                result = "1";
            }

        }

        Response.Write(result);
        Response.End();



    }

    private string getSql(string[] ArrStr, String courseID) {
        string SQL = "";
        //难度_知识点_题型_数量
        Random rnd = new Random(unchecked((int)DateTime.Now.Ticks));
        int intRandomNumber = rnd.Next();
        //"select top 10 * from table order by rnd("+Convert.ToString(-1*intRandomNumber)+"*ID)"

        SQL = "SELECT TOP " + ArrStr[3] + " QuestionId FROM Question WHERE QuestionDifficultyId=" + ArrStr[0] + " AND QuestionKnowledgeId=" + ArrStr[1] + " AND QuestionTypeId=" + ArrStr[2] + " AND CourseId=" + courseID + " ORDER BY RND("+Convert.ToString(-1*intRandomNumber)+"*QuestionId)";
        return SQL;
    }
}
